const glob = require('glob')
const fs = require('fs')
const docx = require('docx')
const express = require('express')
const app = express()
const port = 3002
const fileUpload = require('express-fileupload')
const gm = require('gm').subClass({ imageMagick: true })
const {
    Document,
    PageBreak,
    Paragraph,
    SectionType,
    TextRun,
    Packer,
    ImageRun,
    TextWrappingType,
    TextWrappingSide
} = require('docx')

const inputDir = './input/'
app.get('/', (req, res) => {
    res.send('Hello World!<a href="index.html">生成</a>')
})
const pfg2png = function (file) {
    return new Promise(function (resolve, reject) {
        gm(file)
          .setFormat('png')
          .quality(100)
          .density(300)
          .toBuffer(function (err, buffer) {
              if (err) reject(err)
              resolve(buffer)
          })
    })
}

const build = async function (files) {
    let contents = []
    for (let i = 0; i < files.length; i++) {
        const file = files[i]
        let content = ''
        if (file.mimetype.includes('pdf')) {
            //
            // const png = await pdfToPng(file, {
            //     disableFontFace: false,
            //     useSystemFonts: true
            // })
            // content = png[0].content
            content = await pfg2png(file.data)

        } else {
            content = file.data

        }
        contents.push(content)
    }
    //  console.log(contents)
    let body = []
    const chunkSize = 2
    for (let i = 0; i < contents.length; i += chunkSize) {
        const chunk = contents.slice(i, i + chunkSize)

        for (let j = 0; j < chunk.length; j++) {
            body.push(new Paragraph({
                spacing: {
                    before: 500,
                    after: 300,
                },
                children: [
                    new ImageRun({
                        data: chunk[j],
                        transformation: {
                            width: 600,
                            height: 400
                        }
                    })
                ]
            }))
            // body.push(new Paragraph({
            //     spacing: {
            //         before: 100,
            //     },
            //     children: [
            //         //new TextRun('ss'),
            //
            //         ...chunk.map(function (str) {
            //             return new ImageRun({
            //                 data: str,
            //                 transformation: {
            //                     width: 600,
            //                     height: 400
            //                 }
            //             })
            //         }),
            //
            //         new PageBreak()
            //     ],
            // }))
        }
        body.push(new PageBreak())
    }
    const doc = new Document({
        sections: [
            {
                properties: {
                    type: SectionType.CONTINUOUS,
                },
                children: body
            }
        ]
    })
    const out = './public/' + (new Date()).getTime() + '.docx'
    const buf = (await Packer.toBuffer(doc))
    fs.writeFileSync(out, buf)
    return out
}
const test = function () {
    return new Promise(function (resolve, reject) {
        glob(inputDir + '*.+(pdf|jpg|png)', { nodir: true }, async function (err, files) {
            if (err) {
                console.log('未找到pdf或者图片')
                console.error(err)
                return
            }

            //wkhtmltopdf('', { output: 'out.pdf' })
        })
    })
}

app.use(express.static('public'))
app.use(fileUpload())
app.post('/upload', async (req, res) => {
    // We'll handle the image upload here
    const { image } = req.files
    const files = []
    for (let i = 0; i < image.length; i++) {
        if (image[i].mimetype.includes('image') || image[i].mimetype.includes('pdf')) {
            files.push(image[i])
        }
    }

    const out = await build(files)
    res.download(out)
})
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})